package com.leetcode.LeetCode精选TOP面试题;

import com.leetcode.common.model.ListNode;

/**
 * @author 覃国强
 * @date 2022-05-09 16:23
 */
public class 题库_0002_两数相加 {

  static
  class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      ListNode head = new ListNode();
      ListNode cur = head;
      int carry = 0;
      while (l1 != null || l2 != null) {
        int num1 = l1 != null ? l1.val : 0;
        int num2 = l2 != null ? l2.val : 0;
        int sum = carry + num1 + num2;
        carry = sum / 10;
        sum = sum % 10;
        cur.next = new ListNode(sum);
        cur = cur.next;
        if (l1 != null) {
          l1 = l1.next;
        }
        if (l2 != null) {
          l2 = l2.next;
        }
      }
      if (carry != 0) {
        cur.next = new ListNode(carry);
      }
      return head.next;
    }

  }

}
